from flask import jsonify, request
from ..models.payment import Payment
from ..models.user import User
from ..models.house import House
from ..models.parking_space import ParkingSpace
from ..extensions import db
from ..utils.response import pagination, error, success

# 创建缴费记录
def create_payment():
    try:
        data = request.json
        
        # 验证必填字段
        if not data.get('name') or data.get('amount') is None:
            return error('费用名称和金额为必填字段', 400)
        
        
        # 验证金额必须大于0
        amount = float(data['amount'])
        if amount <= 0:
            return error('费用金额必须大于0', 400)
        
        # 创建缴费实例
        payment = Payment(
            user_id=data.get('user_id'),
            house_id=data.get('house_id'),
            parking_id=data.get('parking_id'),
            name=data['name'],
            description=data.get('description'),
            amount=amount,
            is_paid=data.get('is_paid', False)
        )
        
        db.session.add(payment)
        db.session.commit()
        
        return success(msg='缴费记录创建成功')
    except ValueError:
        return error('金额格式不正确', 400)
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 获取缴费列表
def get_payments(data):
    """获取缴费列表，支持按用户ID、支付状态筛选，支持分页"""
    try:
        is_paid = data.get('is_paid')
        name = data.get('name')
        amount = data.get('amount')

        # 以缴费表 Payment 为主表，所有关联表使用 LEFT JOIN
        query = (
            db.session.query(
                Payment.id,
                Payment.user_id,
                Payment.house_id,
                Payment.parking_id,
                Payment.name.label('payment_name'),
                Payment.description,
                Payment.amount,
                Payment.is_paid,
                Payment.created_at,
                User.name.label('user_name'),
                House.name.label('house_name'),
                ParkingSpace.location.label('parking_location'),
            )
            .outerjoin(User, Payment.user_id == User.id)
            .outerjoin(House, Payment.house_id == House.id)
            .outerjoin(ParkingSpace, Payment.parking_id == ParkingSpace.id)
        )

        # 条件筛选
        if name:
            query = query.filter(Payment.name.like(f'%{name}%'))

        if amount is not None:
            query = query.filter(Payment.amount == float(amount))

        if is_paid is not None:
            query = query.filter(Payment.is_paid == bool(int(is_paid)))

        # 获取总数（基于主表 Payment）
        total = query.count()

        # 排序与分页
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        page = max(page, 1)
        page_size = max(1, min(page_size, 100))

        payments = (
            query.order_by(Payment.created_at.desc())
            .offset((page - 1) * page_size)
            .limit(page_size)
            .all()
        )

        # 转换为字典
        result = []
        for row in payments:
            mapping = dict(row._mapping)
            # 避免 None 报错
            result.append({
                "id": mapping.get("id"),
                "user_id": mapping.get("user_id"),
                "user_name": mapping.get("user_name") or "",
                "house_id": mapping.get("house_id"),
                "house_name": mapping.get("house_name") or "",
                "parking_id": mapping.get("parking_id"),
                "parking_location": mapping.get("parking_location") or "",
                "payment_name": mapping.get("payment_name") or "",
                "description": mapping.get("description") or "",
                "amount": mapping.get("amount"),
                "is_paid": mapping.get("is_paid"),
                "created_at": mapping.get("created_at"),
            })

        return pagination(items=result, total=total, msg='获取成功', code=200)

    except Exception as e:
        print(f"[get_payments error] {e}")
        # 出错时仍返回空数据结构
        return pagination(items=[], total=0, msg='获取失败', code=500)

# 获取单个缴费记录
def get_payment(data):
    try:
        payment_id = data.get('id')
        
        if not payment_id:
            return error('未提供缴费ID', 400)
        
        payment = Payment.query.get(payment_id)
        
        if not payment:
            return error('缴费记录不存在', 404)
        
        return success(msg='获取成功',data=payment.to_dict())
    except Exception as e:
        return error(str(e), 500)

# 更新缴费记录
def update_payment():
    try:
        data = request.json
        payment_id = data.get('id')
        
        if not payment_id:
            return error('未提供缴费ID', 400)
        
        # 连表查询
        payment = Payment.query.get(payment_id)
        
        if not payment:
            return error('缴费记录不存在', 404)
        
        # 更新字段
        if 'name' in data:
            payment.name = data['name']
        if 'description' in data:
            payment.description = data['description']
        if 'amount' in data:
            amount = float(data['amount'])
            if amount <= 0:
                return error('费用金额必须大于0', 400)  
            payment.amount = amount
        if 'is_paid' in data:
            payment.is_paid = data['is_paid']
        if 'house_id' in data:
            payment.house_id = data['house_id']
        if 'parking_id' in data:
            payment.parking_id = data['parking_id']
        if 'user_id' in data:
            payment.user_id = data['user_id']
        # user_id 不允许修改，保持数据一致性
        
        db.session.commit()
        
        return success(msg='更新成功')
    except ValueError:
        return error('金额格式不正确', 400)
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 删除缴费记录
def delete_payment():
    try:
        data = request.json
        payment_id = data.get('id')
        
        if not payment_id:
            return error('未提供缴费ID', 400)
        
        payment = Payment.query.get(payment_id)
        
        if not payment:
            return error('缴费记录不存在', 404)
        
        # 可以添加业务逻辑限制，比如已支付的费用不能删除
        # if payment.is_paid:
        #     return jsonify({'error': '已支付的费用不能删除'}), 400
        
        db.session.delete(payment)
        db.session.commit()
        
        return success(msg='删除成功')  
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)
